<template>
  <div>
    <div class="file-container">
      <el-container>
        <el-main>
          <el-row>
            <el-form :inline="true" size="small" :model="fileFormInline" class="demo-form-inline"
                     @keyup.enter.native="fileQuery" @submit.native.prevent>
              <el-form-item>
                <el-button type="primary" icon="el-icon-plus"
                           v-if="permissions.indexOf('file_add') > -1" @click="fileOpenCreateDialog">添加
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-input v-model="filePageData.query.fileName" placeholder="文件名称"/>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="fileQuery">查询</el-button>
                <el-button class="margin-left-10" icon="el-icon-delete" @click="fileReset">清空
                </el-button>
              </el-form-item>
              <el-tooltip effect="dark" content="刷新" placement="top-start">
                <el-button size="small" style="float: right;" icon="el-icon-refresh" @click="fileQuery"
                           circle></el-button>
              </el-tooltip>
            </el-form>
          </el-row>
          <el-table
              border
              stripe
              size="mini"
              :data="filePageData.pageInfo.records"
              highlight-current-row
              ref="fileTable">
            <el-table-column label="序号" width="80" align="center">
              <template slot-scope="scope">
                <span>{{scope.$index+(filePageData.pageInfo.current - 1) * filePageData.pageInfo.size + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bucketName" label="空间名称" align="center" show-overflow-tooltip/>
            <el-table-column prop="fileName" label="文件名称" align="center" show-overflow-tooltip/>
            <el-table-column prop="originalName" label="原文件名称" align="center" show-overflow-tooltip/>
            <el-table-column prop="fileType" label="文件类型" align="center" show-overflow-tooltip/>
            <el-table-column prop="fileSize" label="文件大小" align="center" show-overflow-tooltip/>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip/>
            <el-table-column label="操作" width="200px" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" icon="el-icon-delete"
                           @click="fileDeleteRecord(scope.row)"
                           v-if="permissions.indexOf('file_del') > -1">删除
                </el-button>
                <el-button type="text" size="small" icon="el-icon-delete"
                           @click="preview(scope.row)">预览
                </el-button>
                <el-button type="text" size="small" icon="el-icon-delete"
                           @click="fileDownload(scope.row)">下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="end" v-show="filePageData.pageInfo.total>0">
            <el-pagination class="pageBar"
                           background
                           @size-change="fileSizeChange"
                           @current-change="fileCurrentChange"
                           :current-page="filePageData.pageInfo.pageNum"
                           :page-sizes="[5, 10, 20, 30, 50]"
                           :page-size="filePageData.pageInfo.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="filePageData.pageInfo.total">
            </el-pagination>
          </el-row>
        </el-main>
      </el-container>
      <el-dialog
          customClass="fileIndex"
          :title="fileDialogData.fileTitle"
          :visible.sync="fileDialogData.visible"
          width="600px"
          append-to-body="true"
          @close="cancelFileDialog()">
        <el-container>
          <el-main>
            <label>文件上传:</label>
            <el-upload
                    ref="myUpload"
                accept="*.*"
                class="upload-demo"
                action="#"
                :limit="1"
                :multiple="false"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :show-file-list="true"
                :auto-upload="false">
              <el-button icon="el-icon-document" type="primary">请选择文件...</el-button>
            </el-upload>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer" v-show="!isFileLook">
          <el-button @click="uploadFile" type="primary">确 定</el-button>
          <el-button @click="cancelFileDialog">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog
          customClass="fileIndex"
          :title="previewDialog.title"
          :visible.sync="previewDialog.visible"
          width="600px"
          append-to-body="true"
          @close="cancelPreview()">
        <el-container>
          <el-main>
            <component :is="currentComponent" :url="url"></component>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelPreview">关闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import fileApi from "./api/file.service"
import IMGS from "./imgs";
import MP3 from "./MP3";
import MP4 from "./MP4";

export default {
  components: {
    IMGS,
    MP3,
    MP4
  },
  data() {
    return {
      fileRules: {
        fileName: [
          {
            required: true,
            message: '文件名称不能为空！'
          },
        ],
      },
      permissions: JSON.parse(sessionStorage.getItem('permissions')),
      fileFormInline: {},
      isFileLook: false,
      previewDialog: {
        visible: false,
        title: "预览",
      },
      fileDialogData: {
        visible: false,
        fileTitle: "",
        fileFormData: {
          fileName: "",
        },
      },
      fileRaw: "",
      filePageData: {
        query: {
          fileName: "",
        },
        pageInfo: {
          size: 10,
          current: 1,
          total: 0
        }
      },
      currentComponent:"",
      url:""
    };
  },
  created() {
    this.fileQuery();
  },
  methods: {
    /**
     * 备注查询
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileQuery() {
      let _this = this;
      fileApi.getFilePage(
        Object.assign({
          current: this.filePageData.pageInfo.current,
          size: this.filePageData.pageInfo.size
        }, this.filePageData.query)
      ).then((res) => {
        _this.filePageData.pageInfo = res.data;
      })
    },
    /**
     * 备注查询重置
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileReset() {
      this.filePageData.query.fileName = "";
      this.fileQuery();
    },

    /**
     * 备注页码变化
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileSizeChange(val) {
      this.filePageData.pageInfo.size = val;
      this.fileQuery();
    },

    /**
     * 备注当前页
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileCurrentChange(val) {
      this.filePageData.pageInfo.current = val;
      this.fileQuery();
    },

    /**
     * 备注添加
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileOpenCreateDialog() {
      this.fileDialogData.fileTitle = "添加";
      this.fileDialogData.visible = true;
      this.fileRaw = "";
      this.fileDialogData.fileFormData = {
        fileName: "",
      };
    },

    uploadFile() {
      let _this = this;
      let formdata = new FormData();
      if (this.fileRaw) {
        formdata.append('file', this.fileRaw);
        fileApi.uploadFile(formdata).then(res => {
          this.$refs['myUpload'].clearFiles();
          this.fileDialogData.visible = false;
          this.fileQuery();
        })
      } else {
        this.$message({
          type: "error",
          message: "请选择文件！"
        })
      }
    },

    handleChange(file) {
      this.fileRaw = file.raw
    },
    handleRemove(file) {
      this.fileRaw = "";
    },

    /**
     * 备注关闭
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    cancelFileDialog() {
      this.$refs['myUpload'].clearFiles();
      this.fileDialogData.visible = false;
      this.isFileLook = false;
      this.fileRaw = "";
    },

    /**
     * 备注删除
     * @author wangwuhui
     * @date 2020-08-10 17:04:49
     */
    fileDeleteRecord(data) {
      if (data.id <= 0) {
        this.$alert('请先选择一条要删除的记录！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        return;
      }

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fileApi.deleteFile(data.id).then((res) => {
          if (res.data > 0) {
            this.$message({
              type: 'success',
              message: '备注删除成功!'
            });
            this.fileQuery();
          } else {
            this.$message({
              type: 'error',
              message: '备注删除失败!'
            });
          }

        });
      });
    },

    /**
     * 下载
     * @param row
     */
    fileDownload(row) {
      fileApi.downloFile(row).then((res) => {
        console.log("123");
      })
    },
    /**
     * 预览
     * @param row
     */
    preview(row) {
      switch (true) {
        case /png|svg|jpg|gif/.test(row.fileType):
          this.currentComponent = "IMGS";
          break;
        case /mp3/.test(row.fileType):
          this.currentComponent = "MP3";
          break;
        case /mp4/.test(row.fileType):
          this.currentComponent = "MP4";
          break;
        default:
          this.currentComponent = "";
          break;
      }
      // TODO URL未赋值 需和后端联调
      // this.url = `http://172.16.5.21:9000/minio/tpf/${row.fileName}`;
      // this.url = "http://localhost:83/background.png";
      this.previewDialog.visible = true;
    },

    /**
     * 关闭预览
     */
    cancelPreview() {
      this.previewDialog.visible = false;
    },

  }
};
</script>
